<?php
/*
 * @Author: lokei
 * @Date: 2023-10-24 16:47:58
 * @LastEditors: lokei
 * @LastEditTime: 2023-10-24 17:34:05
 * @Description: 
 */

namespace App\Common\Douyin;

class Sign {
    public static function sign($map) {
        $rList = [];
        foreach($map as $k =>$v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
                continue;
    
            $value = trim(strval($v));
            if (is_array($v)) {
              $value = Sign::arrayToStr($v);
            }
    
            $len = strlen($value);
            if ($len > 1 && substr($value, 0,1)=="\"" && substr($value, $len-1)=="\"")
                $value = substr($value,1, $len-1);
            $value = trim($value);
            if ($value == "" || $value == "null")
                continue;
            $rList[] = $value;
        }
        $rList[] = "7NjxxL3w0iL75DvcATP9yU1C1ywFO6B6l2PwS4ks";
        sort($rList, SORT_STRING);
        return md5(implode('&', $rList));
    }
    
    private static function arrayToStr($map) {
      $isMap = Sign::isArrMap($map);
    
        $result = "";
        if ($isMap){
          $result = "map[";
        }
    
        $keyArr = array_keys($map);
        if ($isMap) {
            sort($keyArr);
        }
    
        $paramsArr = array();
        foreach($keyArr as  $k) {
          $v = $map[$k];
          if ($isMap) {
            if (is_array($v)) {
              $paramsArr[] = sprintf("%s:%s", $k, Sign::arrayToStr($v));
            } else  {
              $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
            }
          } else {
            if (is_array($v)) {
              $paramsArr[] = Sign::arrayToStr($v);
            } else  {
              $paramsArr[] = trim(strval($v));
            }
          }
        }
    
        $result = sprintf("%s%s", $result, join(" ", $paramsArr));
        if (!$isMap) {
          $result = sprintf("[%s]", $result);
        } else {
          $result = sprintf("%s]", $result);
        }
    
        return $result;
    }
    
    private static function isArrMap($map) {
        foreach($map as $k =>$v) {
          if (is_string($k)){
              return true;
          }
        }
    
        return false;
    }
}
